<?php

namespace App\Tools;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class AliyunSmsTool {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => 'LTAI5tJhMN9a8udJUJvHCxBF',
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => 'eugqgZ3VeAsiIkrEntWJzK3D9N47Ir'
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param $phone
     * @param $code
     * @return bool
     */
    public static function main($phone, $code):bool
    {
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient("accessKeyId", "accessKeySecret");
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => "$phone",
            "signName" => "猴人网络",
            "templateCode" => "SMS_222805052",
            "templateParam" => "{\"code\":\"$code\"}"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $client->sendSmsWithOptions($sendSmsRequest, $runtime);

            return true;
        }
        catch (Exception $error) {
            writeLoToFile('send_tel_code', '短信发送失败：', json_encode($sendSmsRequest));

            return false;
        }
    }

    /**
     * @param $phone
     * @param $number
     */
    public static function mainMessage($phone, $number)
    {
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient("accessKeyId", "accessKeySecret");
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => "河北新牧农农业科技",
            "templateCode" => $number
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);

            return true;
        }
        catch (Exception $error) {
            writeLoToFile('send_tel_code', '短信发送失败：', json_encode($sendSmsRequest));

            return false;
        }
    }
}
